<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php

/**
 * Try to create a short identifier by cutting out the hostname part of the Open ID.
 * @param string $identityUrl OpenID
 * @return string short identifier
 */
function escape_getOpenIdShortIdentifier($identityUrl)
{
	$shortIdentifier = $identityUrl;
	if(preg_match('~[a-z]+:/*([a-z0-9.]+)~i', $identityUrl, $matches))
	{
		$shortIdentifier = $matches[1];
	}
	return $shortIdentifier;
}

/**
 * Do a HTTP GET request and return the result as a string.
 * @param string $url URL
 * @param string $data GET data, create using: http_build_query()
 * @param array $optional_headers Optional headers
 * @return string Response string
 */
function escape_doGetRequest($url, $data, $optional_headers = null, $username = null, $password = null)
{
	$params = array('http' => array(
								'method' => 'GET',
					));
		
	if($username !== null)
	{
		if($optional_headers === null)
		{
			$optional_headers = '';
		}
		$optional_headers = "Authorization: Basic " . base64_encode($username . ':' . $password) . "\r\n" . $optional_headers;
	}
	
	if($optional_headers !== null) {
		$params['http']['header'] = $optional_headers;
	}
	
	$ctx = stream_context_create($params);
	
	if($data !== null)
	{
		$url .= '?' . $data;
	}
	$handle = @fopen($url, 'rb', false, $ctx);
	if(!$handle)
	{
		throw new Exception("Problem with " . $url);
	}
	
	$response = @stream_get_contents($handle);
	if ($response === false)
	{
		throw new Exception("Problem reading data from " . $url);
	}
	
	fclose($handle);
	
	return $response;
}

/**
 * Do a HTTP DELETE request and return the result as a string.
 * @param string $url URL
 * @param string $data GET data, create using: http_build_query()
 * @param array $optional_headers Optional headers
 * @return string Response string
 */
function escape_doDeleteRequest($url, $data, $optional_headers = null, $username = null, $password = null)
{
	$params = array('http' => array(
								'method' => 'DELETE',
					));
		
	if($username !== null)
	{
		if($optional_headers === null)
		{
			$optional_headers = '';
		}
		$optional_headers = "Authorization: Basic " . base64_encode($username . ':' . $password) . "\r\n" . $optional_headers;
	}
	
	if($optional_headers !== null) {
		$params['http']['header'] = $optional_headers;
	}
	
	$ctx = stream_context_create($params);
	
	if($data !== null)
	{
		$url .= '?' . $data;
	}
	$handle = @fopen($url, 'rb', false, $ctx);
	if(!$handle)
	{
		throw new Exception("Problem with " . $url);
	}
	
	$response = @stream_get_contents($handle);
	if ($response === false)
	{
		throw new Exception("Problem reading data from " . $url);
	}
	
	fclose($handle);
	
	return $response;
}

/**
 * Escape a string for placing it in a JavaScript string. 
 * @param string $string String
 * @return string Escaped string
 */
function escape_javascriptEscape($string)
{
	return preg_replace("/\r?\n/", "\\n", addslashes($string));
}

/**
 * Display a variable using print_r, HTML escaped in a <pre> section 
 * @param $var Variable
 */
function escape_printr_pre($var)
{
	print '<pre class="escape_PreWrap">';
	print htmlspecialchars(print_r($var, true));
	print '</pre>';
}

/**
 * Check if the current request is made using Microsoft Internet Explorer.
 * @return boolean True if the current request is made using Microsoft Internet Explorer
 */
function escape_isBrowserInternetExplorer()
{
	if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
	{
		return true;
	}
	else
	{
		return false;
	}
}

/**
 * Test if a string is a valid URI.
 * @param string $uri URI
 * @return boolean True if the URI specified is a valid URI
 */
function escape_isValidUri($uri)
{
	return preg_match("~^([a-z0-9+.-]+):(?://(?:((?:[a-z0-9-._\\~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?((?:[a-z0-9-._\\~!$&'()*+,;=]|%[0-9A-F]{2})*)(?::(\d*))?(/(?:[a-z0-9-._\\~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?|(/?(?:[a-z0-9-._\\~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._\\~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?)(?:\?((?:[a-z0-9-._\\~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._\\~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?$~i", $uri);
}

/**
 * Encrypt data using a symmetric encryption algorithm.
 * @param string $data data
 * @param string $password password
 * @return string encrypted data (binary)
 */
function escape_encryptData($data, $password)
{
	// convert the password to a 256 bit key using a SHA256 on the binary text data 
	$key = hash('sha256', $password, true);
	
	// generate a random initialization vector
	$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB);
	$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);

	// encrypt the data
	$encryptedData = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CFB, $iv);
	
	// concatenate the initialization vector and the encrypted fata
	$result = $iv . $encryptedData;
	
	return $result;
}

/**
 * Decrypt data using a symmetric encryption algorithm.
 * @param string $encryptedData encrypted data (binary)
 * @param string $password password
 * @return string data
 */
function escape_decryptData($encryptedData, $password)
{
	// convert the password to a 256 bit key using a SHA256 on the binary text data 
	$key = hash('sha256', $password, true);

	// fetch the the initialization vector
	$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB);
	$iv = substr($encryptedData, 0, $ivSize);
	
	// fetch the crypttext
	$encryptedData = substr($encryptedData, $ivSize);

	// decrypt the data
	$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encryptedData, MCRYPT_MODE_CFB, $iv);
	
	return $data;
}
